//
//  ChivoxAiEngine.m
//  ChivoxEngine
//
//  Created by John on 2018/8/24.
//  Copyright © 2018年 Chivox. All rights reserved.
//

#import "ChivoxWsEngine.h"
#import <CommonCrypto/CommonDigest.h>
#import "SocketRocket.h"
#define dispatch_main_async_safe(block)\
if ([NSThread isMainThread]) {\
block();\
} else {\
dispatch_async(dispatch_get_main_queue(), block);\
}

@implementation ChivoxWsEngine
- (void)ChivoxWebSocket:(NSString *)url{
    //self
    self.socket = [[SRWebSocket alloc]initWithURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]] ];
    self.socket.delegate = self;
    [self.socket open];
}
- (void)getrequest{
    int recordTime = [[NSDate date] timeIntervalSince1970 ]*1000l;
    NSString *timestamp = [NSString stringWithFormat:@"%d",recordTime];
    NSString *str = [NSString stringWithFormat:@"%@%d%@",self.appKey,recordTime,self.secretKey];
    NSString *sig = [self md5:str];
    NSMutableDictionary *app = [[NSMutableDictionary alloc]init];
    [app setObject:self.appKey forKey:@"applicationId"];
    [app setObject:sig forKey:@"sig"];
    [app setObject:@"md5" forKey:@"alg"];
    [app setObject:self.Useid forKey:@"useId"];
    NSMutableDictionary *request = [[NSMutableDictionary alloc]init];
    [request setObject:app forKey:@"app"];
    NSData *data=[NSJSONSerialization dataWithJSONObject:request options:NSJSONWritingPrettyPrinted error:nil];
    NSString *strre=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    [self sendData:strre];
}
- (NSString *) md5:(NSString *) input
{
    const char *cStr = [input UTF8String];
    unsigned char digest[16];
    CC_MD5( cStr, strlen(cStr), digest ); // This is the md5 call
    
    NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    
    for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
        [output appendFormat:@"%02x", digest[i]];
    return  output;
    
}
- (void)webSocketDidOpen:(SRWebSocket *)socket{
    NSLog(@"连接成功");
    //开启心跳
    [self getrequest];
}
- (void)webSocket:(SRWebSocket *)webSocket didFailWithError:(NSError *)error {
    NSLog(@"连接失败：%@",error);
    
}
- (void)webSocket:(SRWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(NSString *)reason wasClean:(BOOL)wasClean {
    NSLog(@"连接断开");
}
#define WeakSelf(ws) __weak __typeof(&*self)weakSelf = self
- (void)sendData:(id)data {
    NSLog(@"socketSendData --------------- %@",data);
    
    WeakSelf(ws);
    dispatch_queue_t queue =  dispatch_queue_create("zy", NULL);
    
    dispatch_async(queue, ^{
        if (weakSelf.socket != nil) {
            // 只有 SR_OPEN 开启状态才能调 send 方法啊，不然要崩
            if (weakSelf.socket.readyState == SR_OPEN) {
                [weakSelf.socket send:data];    // 发送数据
                
            } else if (weakSelf.socket.readyState == SR_CONNECTING) {
                
            } else if (weakSelf.socket.readyState == SR_CLOSING || weakSelf.socket.readyState == SR_CLOSED) {
            }
        } else {

        }
    });
}
- (void)webSocket:(SRWebSocket *)webSocket didReceiveMessage:(id)message  {
    
    if (webSocket == self.socket) {
        NSLog(@"message:%@",message);
        [self.engineDagete initCallback:self Ret:1 Msg: @"cad"];
    }
}

@end
